import { Popup, Tabs } from "antd-mobile";
import { CloseOutline } from "antd-mobile-icons";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import styles from "./index.module.less";

export const ArticlePopup = forwardRef(({ article }, ref) => {
  const [popupVisible, setPopupVisible] = useState(false);
  const [content, setContent] = useState("");

  useImperativeHandle(ref, () => {
    return {
      open: openPopup,
      close: closePopup,
    };
  });

  const openPopup = () => {
    setPopupVisible(true);
  };
  const closePopup = () => {
    setPopupVisible(false);
  };

  useEffect(() => {
    setContent(
      article?.children ? article.children[0].content : article?.content,
    );
  }, [article]);

  return (
    <Popup
      visible={popupVisible}
      bodyStyle={{ height: "80vh" }}
      className={styles.bottomPopupContainer}
      destroyOnClose
    >
      {article && (
        <div className={"detail"}>
          <div className={"head"}>
            {article.title}
            <CloseOutline className={"close"} onClick={closePopup} />
          </div>
          {article.children && (
            <div className={"tabs"}>
              <Tabs
                onChange={(index) =>
                  setContent(article.children[index].content)
                }
              >
                {article.children.map((item, index) => (
                  <Tabs.Tab title={item.title} key={index} />
                ))}
              </Tabs>
            </div>
          )}
          <div
            className={"content"}
            dangerouslySetInnerHTML={{ __html: content }}
          ></div>
        </div>
      )}
    </Popup>
  );
});
